from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from evaluate.jsonTools.studentEJson import Term_freshair,st_organization_total
from django.views.decorators.csrf import csrf_exempt
from .evaluateTools import get_advice
from .models import EvaluateAdmin,Function,StudentGrade,CourseTimetable,StudentEvaluateTeacher,StudentAhp,CountTeacher,Teacher
from .models import CountTeacher,PeopleCount
from .checkLogin import check_admin
import random

#admin登陆
def admin_login(request):
	login_error=''
	if request.method=='POST':
		admin=check_pwd(request)	
		if admin:
			request.session['u_id'] = admin.id
			request.session['u_type'] =admin.admin_type
			return HttpResponseRedirect('/evaluate/admin_index/')
		login_error='账号密码错误'
	return render(request,'evaluate/admin/login.html',{'login_error':login_error})



#验证用户密码
@csrf_exempt
def check_pwd(request):
	u_id = request.POST['u_id']
	pwd = request.POST['pwd']
	admin_list = EvaluateAdmin.objects.filter(id=u_id,pwd=pwd)
	if admin_list:
		admin=admin_list[0]
		return admin
	return False

#admin修改密码
@csrf_exempt
def  change_pwd(request):
	if request.method=='POST':
		admin=check_pwd(request)
		message='输入错误'
		if admin:
			admin.pwd = request.POST['new_pwd']
			admin.save()
			message = '修改成功'
		return render(request,'evaluate/admin/changePwd.html',{'message':message})
	return  render(request,'evaluate/admin/changePwd.html')


#超级管理员增加管理员
@csrf_exempt
def add_admin(request):
	if request.method=='POST':
		try:
			u_id = request.POST['u_id']
			pwd = request.POST['pwd']
			EvaluateAdmin.objects.create(id=u_id,pwd=pwd,admin_type='管理员')
			message = '添加成功'
		except:
			message ='添加失败'
		return render(request,'evaluate/admin/addAdmin.html',{'message':message})
	return  render(request,'evaluate/admin/addAdmin.html')

#开启评价系统主页
def opend_evaluate_index(request):
	year=Function.objects.exclude(state='end')[:1][0]
	return render(request,'evaluate/admin/openFunction.html',{'year':year})

#开启当学期系统
def opend_evaluate(request):
	year=Function.objects.exclude(state='end')[:1][0]
	year.state='active'  #启动系统
	year.save()
	return HttpResponseRedirect('/evaluate/opend_evaluate_index/')

#结束当学期系统
def close_evaluate(request):
	year=Function.objects.exclude(state='end')[:1][0]
	year.state='close'  #关闭当学期系统
	year.save()
	return HttpResponseRedirect('/evaluate/opend_evaluate_index/')

#启动离线计算当学期评价数据主页
def count_evaluation_index(request):
	year=Function.objects.exclude(state='end')[:1][0]
	year_lately=Function.objects.filter(state='end').order_by('-id')[:1]
	if year_lately:
		year_lately=year_lately[0]
	else:
		year_lately='false'
	return render(request,'evaluate/admin/countEvaluation.html',{'year':year,'year_lately':year_lately})

#分析评价数据
def count_evaluation(request):
	year=Function.objects.exclude(state='end')[:1][0]
	year.state='end'  #关闭当学期系统
	year.save()
	StudentGrade.objects.all().delete() #清除上一阶段数据
	StudentEvaluateTeacher.objects.all().delete()
	create_data(year.year_term)
	return HttpResponse(u'成功')

"""处理评价数据"""

#产生模拟数据
def create_data(year_term):
	
	#模拟学生评价教师
	course_list = CourseTimetable.objects.all() #课表
	for course in course_list:
		s='14073002'
		i=1
		while i<=90:
			a=random.randint(2,5)
			b=random.randint(2,5)
			c=random.randint(2,5)
			grade=random.randint(50, 100)
			if i<10:
				s='140730020'+str(i) 	
			StudentEvaluateTeacher.objects.create(student_id=s,teacher_id=course.teacher_id,class_id=course.course_id,class_mien=a,after_school_program=b,teacher_charm=c)
			StudentGrade.objects.create(student_id=s,teacher_id=course.teacher_id,course_id=course.course_id,grade=grade)
			i+=1
	count_teacher(year_term) 

#计算教师得分
def count_teacher(year_term):
	course_list = CourseTimetable.objects.all() #课表
	student_ahp=StudentAhp.objects.all()[:1][0]
	for course in course_list:
		bad_num=0
		bad_sum=0
		conformity_num=0
		conformity_sum=0
		good_num=0
		good_sum=0
		excellent_num=0
		excellent_sum=0
		excellent=0  
		conformity=0
		num=0
		student_grade_list = StudentGrade.objects.filter(teacher_id=course.teacher_id,course_id=course.course_id)
		for student_grade in student_grade_list:
			s_e=StudentEvaluateTeacher.objects.filter(class_id=student_grade.course_id,student_id=student_grade.student_id)
			if s_e:
				num+=1
				s_e=s_e[0]
				if student_grade.grade<60:
					bad_num+=1
					bad_sum+=(s_e.class_mien+s_e.after_school_program+s_e.teacher_charm)/3*student_ahp.bad
				elif student_grade.grade<75:
					good_num+=1
					conformity+=1
					good_sum+=(s_e.class_mien+s_e.after_school_program+s_e.teacher_charm)/3*student_ahp.good
				elif student_grade.grade<90:
					conformity_num+=1
					conformity+=1
					conformity_sum+=(s_e.class_mien+s_e.after_school_program+s_e.teacher_charm)/3*student_ahp.conformity
				else:
					excellent+=1
					excellent_num+=1
					conformity+=1
					excellent_sum+=(s_e.class_mien+s_e.after_school_program+s_e.teacher_charm)/3*student_ahp.excellent
		grade=0
		if bad_num!=0:
			grade+=bad_sum/bad_num
		if good_num !=0:
			grade+=good_sum/good_num		
		if conformity_num !=0:
			grade+=conformity_sum/conformity_num	
		if excellent_num !=0:
			grade+=excellent_sum/excellent_num
		grade=round(grade,0)
		CountTeacher.objects.create(excellent=round(excellent/num*100,2),conformity=round(conformity/num*100,2),year_term=year_term,class_type=course.class_type,teacher_id=student_grade.teacher_id,course=course.name,grade=grade)

"""处理评价数据end"""


"""
	数据展示
"""

#admin主页
@check_admin
def admin_index(request):
	return render(request,'evaluate/admin/adminIndex.html')

#学生总评评价报表
@csrf_exempt
@check_admin
def s_enviroment_totality(request):
	if request.method=='POST':
		option = Term_freshair('totality')
		return JsonResponse(option)
	term = get_lately_term()
	advice_all = get_advice('totality',term)
	advice_temp = advice_all[:5]
	return render(request,'evaluate/admin/stEvEnviromentTotal.html',{'advice_all':advice_all,"advice_temp":advice_temp,'url':'/evaluate/s_enviroment_totality/','title':'综合环境评价'})


#学生教学环境报表
@csrf_exempt
@check_admin
def s_enviroment_teching(request):
	if request.method=='POST':
		option = Term_freshair('teaching')
		# print(option)
		return JsonResponse(option)
	term = get_lately_term()
	advice_all = get_advice('teaching',term)
	advice_temp = advice_all[:5]
	return render(request,'evaluate/admin/stEvEnviromentTotal.html',{'advice_all':advice_all,"advice_temp":advice_temp,'url':'/evaluate/s_enviroment_teching/','title':'教学环境评价'})


#学生住宿评价报表
@csrf_exempt
@check_admin
def s_enviroment_accommodation(request):
	if request.method=='POST':
		option = Term_freshair('accommodation')
		# print(option)
		return JsonResponse(option)
	term = get_lately_term()
	advice = get_advice('accommodation',term)
	return render(request,'evaluate/admin/stEvEnviromentTotal.html',{'advice':advice,'url':'/evaluate/s_enviroment_accommodation/','title':'住宿环境评价'})


#学生饮食评价报表
@csrf_exempt
@check_admin
def s_enviroment_diet(request):
	if request.method=='POST':
		option = Term_freshair('diet')
		return JsonResponse(option)
	term = get_lately_term()
	advice = get_advice('diet',term)
	return render(request,'evaluate/admin/stEvEnviromentTotal.html',{'advice':advice,'url':'/evaluate/s_enviroment_diet/','title':'饮食环境评价'})

#学生评价校内机构
@csrf_exempt
def s_enviroment_o_total(request):
	if request.method=='POST':
		option = st_organization_total('student')
		return JsonResponse(option)
	return render(request,'evaluate/admin/stOrganization.html',{'url':'/evaluate/s_enviroment_o_total/','title':'对校内机构的评价'})



"""教师数据展示"""


#教师评价校内机构
@csrf_exempt
def t_enviroment_o_total(request):
	if request.method=='POST':
		option = st_organization_total('teacher')
		return JsonResponse(option)
	return render(request,'evaluate/admin/stOrganization.html',{'url':'/evaluate/t_enviroment_o_total/','title':'对校内机构的评价'})

#教师当年得分情况
def teacher_grade_table(request):
	year=Function.objects.filter(state='end').order_by('-id')[:2]
	count_now_list=CountTeacher.objects.filter(year_term=year[0].year_term)
	result_lsit=[]
	for count_now in count_now_list:
		count_ago=CountTeacher.objects.filter(year_term=year[1].year_term,course=count_now.course)[0]
		conformity=count_now.conformity-count_ago.conformity
		excellent=count_now.excellent-count_ago.excellent
		grade=count_now.grade-count_ago.grade
		change_dir={}
		if conformity<0:
			change_dir['conformity_change']=round(abs(conformity),2)
			change_dir['conformity_abs']='down'
		else:
			change_dir['conformity_change']=round(conformity,2)
			change_dir['conformity_abs']='up'
		if excellent<0:
			change_dir['excellent_change']=round(abs(excellent),2)
			change_dir['excellent_abs']='down'
		else:
			change_dir['excellent_change']=round(excellent,2)
			change_dir['excellent_abs']='up'
		if grade<0:
			change_dir['grade_change']=ground(abs(grade),2)
			change_dir['grade_abs']='down'
		else:
			change_dir['grade_change']=round(grade,2)
			change_dir['grade_abs']='up'
		change_dir['t_id']=count_now.teacher_id
		change_dir['t_name']=Teacher.objects.get(teacher_id=count_now.teacher_id).user_name
		change_dir['course']=count_now.course
		change_dir['course_type']=count_now.class_type
		change_dir['grade']=count_now.grade
		change_dir['conformity']=count_now.conformity
		change_dir['excellent']=count_now.excellent
		result_lsit.append(change_dir)
	return render(request,'evaluate/admin/teacherGradeTable.html',{'result_lsit':result_lsit})



"""教师数据展示end"""

#获取最近完成的学期
def get_lately_term():
	term = Function.objects.filter(state="end").order_by('-id')[:1][0]
	return term	


"""
	ajax接口start
"""

#主页数据调用
@csrf_exempt
def people_count(request):
	people_count={}
	year_term_list=[];
	student_list=[];
	teacher_list=[];
	hot_word_list=[];
	advice_list=[];
	year_lately_list=PeopleCount.objects.all().order_by('-id')[:6] #最多比较六年
	for count in year_lately_list[::-1]: #逆序遍历
		year_term_list.append(count.year_term)
		student_list.append(count.student)
		teacher_list.append(count.teacher)
		hot_word_list.append(count.hot_word)
		advice_list.append(count.advice)
	people_count["year_term_list"]=year_term_list
	people_count["student_list"]=student_list
	people_count["teacher_list"]=teacher_list
	people_count["hot_word_list"]=hot_word_list
	people_count["advice_list"]=advice_list
	if year_lately_list:
		count = year_lately_list[0]
		people_count["teacher"]=count.teacher
		people_count["student"]=count.student
		people_count["hot_word"]=count.hot_word
		people_count["advice"]=count.advice
		people_count["teacher_percent"]=count.teacher_percent
		people_count["student_percent"]=count.student_percent
		people_count["year_term"]=count.year_term
	return JsonResponse(people_count)


"""
	ajax接口end
"""

def advice_show(request):
	return render(request,'evaluate/admin/adviceShow.html')

def search(request):
	return render(request,'evaluate/admin/searchData.html')
